package com.yf.login;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.app.Activity;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	private EditText et_username;
	private EditText et_password;
	private CheckBox cb_isSave;
	private Button btn_login;
	private Button btn_fill;
	private MyOpenHelper openHelper;
	
	private Handler handler = new Handler(){
		public void dispatchMessage(android.os.Message msg) {
			String result = (String) msg.obj;
			Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 这里设置布局
		setContentView(R.layout.activity_main);

		openHelper = new MyOpenHelper(this);
		// getReadableDatabase和getWritableDatabase大部分情况下作用相同
		// 当磁盘满的时候前者会返回一个只读数据库，后者会失败
		openHelper.getReadableDatabase();

		et_username = (EditText) findViewById(R.id.et_username);
		et_password = (EditText) findViewById(R.id.et_password);
		cb_isSave = (CheckBox) findViewById(R.id.cb_isSave);
		btn_login = (Button) findViewById(R.id.btn_login);

		btn_login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final String username = et_username.getText().toString().trim();
				final String password = et_password.getText().toString().trim();

				if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
					Toast.makeText(MainActivity.this, "用户名密码不能为空", Toast.LENGTH_SHORT).show();
				} else {
					if (cb_isSave.isChecked()) {
						Log.d("Login", "保存用户名密码");
						SharedPreferences sp = getSharedPreferences("user", MODE_PRIVATE);
						Editor editor = sp.edit();
						editor.putString("username", username);
						editor.putString("password", password);
						editor.commit();

						boolean isSave;
						boolean sdAvailable = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);

						if (sdAvailable) {
							isSave = FileUtil.saveUser2SD(MainActivity.this, new User(username, password));
						} else {
							// boolean isSave = FileUtil.saveUser(new
							// User(username, password));
							isSave = FileUtil.saveUserByContext(MainActivity.this, new User(username, password));
						}

						if (isSave) {
							Toast.makeText(MainActivity.this, sdAvailable ? "用户名密码已保存到SD卡" : "用户名密码已保存到data",
									Toast.LENGTH_SHORT).show();
						}
					}

					new Thread(new Runnable() {
						
						@Override
						public void run() {
							String path = "http://10.0.2.2:8780/LoginServer/login";
							Log.d("Login", path);
							try {
								String params = "username=" + URLEncoder.encode(username, "utf-8") + "&password="
										+ URLEncoder.encode(password, "utf-8");
								URL url = new URL(path);
								Log.d("Login", params);
								HttpURLConnection conn = (HttpURLConnection) url.openConnection();
								conn.setRequestMethod("POST");
								conn.setConnectTimeout(8000);
								conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
								conn.setRequestProperty("Content-Length", String.valueOf(params.length()));
								//打开输出流
								conn.setDoOutput(true);
								//通过流把请求体写到服务端，完成发送请求
								conn.getOutputStream().write(params.getBytes());
								int resCode = conn.getResponseCode();
								
								Log.d("Login", String.valueOf(resCode));
								
								if (resCode == 200) {
									InputStream is = conn.getInputStream();
									String result = StringUtil.fromStream(is);
									Message msg = Message.obtain();
									msg.obj = result;
									handler.sendMessage(msg);
								} else {
									Message msg = Message.obtain();
									msg.obj = "服务器异常";
									handler.sendMessage(msg);
								}

							} catch (Exception e) {
								e.printStackTrace();
								Message msg = Message.obtain();
								msg.obj = "网络异常";
								handler.sendMessage(msg);
							}
						}
					}).start();
				}
			}
		});

		btn_fill = (Button) findViewById(R.id.btn_fill);
		btn_fill.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				User user;

				if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
					user = FileUtil.loadUserFromSD(MainActivity.this);
				} else {
					user = FileUtil.loadUserByContext(MainActivity.this);
				}

				if (user == null) {
					Toast.makeText(MainActivity.this, "用户名密码未保存", Toast.LENGTH_SHORT).show();
				} else {
					et_username.setText(user.getUsername());
					et_password.setText(user.getPassword());
				}
			}
		});
	}

	public void handleReadOther(View v) {
		try {
			String msg = FileUtil.loadMsgByPath("data/data/com.yf.dialup/files/msg.txt");
			Log.v("handleReadFile", msg);
			Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(MainActivity.this, "读取失败", Toast.LENGTH_SHORT).show();
		}
	}

	public void handleReadFromSharedPreferences(View v) {
		try {
			SharedPreferences sp = getSharedPreferences("user", MODE_PRIVATE);
			String username = sp.getString("username", "unknown");
			et_username.setText(username);
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(MainActivity.this, "读取失败", Toast.LENGTH_SHORT).show();
		}
	}

	public void handleSelect(View v) {
		SQLiteDatabase db = openHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select * from user", null);
		// 通过游标遍历结果集
		while (cursor.moveToNext()) {
			String name = cursor.getString(cursor.getColumnIndex("name"));
			Log.v("rawQuery", name);
		}
		db.close();
	}

	public void handleInsert(View v) {
		SQLiteDatabase db = openHelper.getReadableDatabase();
		db.execSQL("insert into user values(null, 'yvan', '13691555967', 2000)");
		db.execSQL("insert into user values(null, 'yaowenjie', '13691555666', 1000)");
		db.close();
	}

	public void handleUpdate(View v) {
		SQLiteDatabase db = openHelper.getReadableDatabase();
		db.execSQL("update user set name = 'yangfeng' where name = 'yvan'");
		db.close();
	}

	public void handleDel(View v) {
		SQLiteDatabase db = openHelper.getReadableDatabase();
		db.execSQL("delete from user where name = 'yangfeng'");
		db.close();
	}

	public void handleSelect2(View v) {
		SQLiteDatabase db = openHelper.getReadableDatabase();
		String[] columns = { "name", "phone" };
		String selection = "name = ?";
		String[] selectionArgs = { "jianyu" };
		String groupBy = null;
		String having = null;
		String orderBy = null;
		Cursor cursor = db.query("user", columns, selection, selectionArgs, groupBy, having, orderBy);

		// 通过游标遍历结果集
		while (cursor.moveToNext()) {
			String name = cursor.getString(cursor.getColumnIndex("name"));
			Log.v("rawQuery", name);
		}

		db.close();
	}

	public void handleInsert2(View v) {
		SQLiteDatabase db = openHelper.getReadableDatabase();
		ContentValues values = new ContentValues();
		values.put("name", "jianyu");
		values.put("phone", "13512345678");
		values.put("amount", 1500);
		// 当column为null时，使用一个列名替换它，避免出现insert into user null values (null);
		String nullColumnHack = "name";
		long id = db.insert("user", nullColumnHack, values);
		Toast.makeText(this, "新插入行id: " + id, Toast.LENGTH_SHORT).show();
		db.close();
	}

	public void handleUpdate2(View v) {
		SQLiteDatabase db = openHelper.getReadableDatabase();
		db.beginTransaction();
		try {
			ContentValues values = new ContentValues();
			values.put("name", "yvan");
			String whereClause = "name = ?";
			String[] whereArgs = new String[] { "yangfeng" };
			int rowCnt = db.update("user", values, whereClause, whereArgs);
			Toast.makeText(this, "更新" + rowCnt + "行", Toast.LENGTH_SHORT).show();

			db.setTransactionSuccessful();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.endTransaction();
			db.close();
		}
	}

	public void handleDel2(View v) {
		SQLiteDatabase db = openHelper.getReadableDatabase();
		String whereClause = "name = ?";
		String[] whereArgs = { "yaowenjie" };
		int rowCnt = db.delete("user", whereClause, whereArgs);
		Toast.makeText(this, "删除" + rowCnt + "行", Toast.LENGTH_SHORT).show();
		db.close();
	}

	public void transferAmount(View v) {
		SQLiteDatabase db = openHelper.getReadableDatabase();
		db.beginTransaction();
		try {
			db.rawQuery("update user set amount=1800 where name=?", new String[] { "yangfeng" });
			int i = 1 / 0;
			db.rawQuery("update user set amount=1400 where name=?", new String[] { "yaowenjie" });
			db.setTransactionSuccessful();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.endTransaction();
			db.close();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
